package com.sy.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sy.dto.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HttpUtils {
    private HttpUtils() {

    }


    public static void writeJson(HttpServletResponse res, Object data) {
        res.setContentType("application/json;charset=utf-8");
        try (PrintWriter out = res.getWriter()) {
            out.write(new ObjectMapper().writeValueAsString(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeJson(HttpServletResponse res, Object data, int code) {
        res.setStatus(code);
        writeJson(res, data);

    }

    public static Result buildSuccess(HttpServletResponse res, Integer code, Object data) {
        Result result = new Result();
        res.setStatus(code);
        result.setCode(code);
        result.setData(data);
        return result;
    }

    public static Result buildFailure(HttpServletResponse res, Integer code, String errMsg) {
        Result result = new Result();
        res.setStatus(code);
        result.setCode(code);
        result.setError(errMsg);
        return result;
    }
    /**
     * 向Session中添加属性
     *
     * @param name  属性名
     * @param value 属性值
     */
    public static void setSessionAttribute(String name, Object value,HttpServletRequest req) {
        req.getSession().setAttribute(name, value);
    }
    /**
     * 从Session中获取属性值
     * @param name 属性名
     * @return 属性值
     */
    public static Object getSessionAttribute(String name,HttpServletRequest req) {
        return req.getSession().getAttribute(name);
    }

}
